package xin.marcher.module.inventory.manage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import xin.marcher.module.inventory.service.InventoryBucketService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 */
@Component
public class OperateClearQueue {

    /**
     * 配置的任务内存队列数量
     */
    @Value("${bucket.operate.queue-num:32}")
    private Integer queueNum;

    /**
     * 处理任务的队列列表
     */
    private final List<BlockingQueue> operateQueue = new ArrayList<>();

    /**
     * 下一个任务处理队列在列表中的下标
     */
    private AtomicInteger index = new AtomicInteger();

    @Resource
    private InventoryBucketService inventoryBucketService;

    @PostConstruct
    public void init() {
        ExecutorService executors = Executors.newFixedThreadPool(queueNum);
        for (int i = 0; i < queueNum; i++) {
            //设置一个队列最大容纳数量
            BlockingQueue blockingQueue = new ArrayBlockingQueue(150000);
            operateQueue.add(blockingQueue);
            executors.execute(new OperateClearRunner(blockingQueue, inventoryBucketService));
        }

    }

    /**
     * 轮询
     *
     * @param object
     * @return
     */
    public boolean offerByRoundRobin(Object object) {
        index.compareAndSet(queueNum * 10000, 0);
        boolean offer = operateQueue.get(index.getAndIncrement() % queueNum).offer(object);
        return offer;
    }

}
